<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/15
 * Time: 14:37
 */

class User extends ADM_Controller
{
    const DEFAULT_LIMIT = 20;

    public function __construct()
    {
        parent::__construct();
    }

    public function add()
    {
        $this->load->view('admin/admin/add_user.html');
    }

    public function edit()
    {
        $this->load->view('admin/admin/edit_user.html');
    }

    public function password()
    {
        $this->load->view('admin/admin/password.html');
    }

    public function editPassword()
    {
        $send['state'] = false;
        do {

            $posts = $this->input->post();
            if (empty($posts)) {
                $send['error'] = '参数错误';
                break;
            }

            if ($posts['newPassword'] != $posts['rePassword']) {
                $send['error'] = '两次密码不一致';
                break;
            }

            $id = adminId();
            $q = $this->db->get_where('admin', ['id' => $id]);
            $item = $q->row_array();
            if (empty($item)) {
                $send['error'] = '无此用户';
                break;
            }

            if (!decryptPassword($posts['password'], $item['password'], $item['salt'])) {
                $send['error'] = '原密码错误';
                break;
            }

            $pass = encryptPassword($posts['newPassword']);
            $this->db->where('id', $id)->update('admin', ['password' => $pass['password'], 'salt' => $pass['salt']]);
            if ($this->db->affected_rows()) {
                $send['state'] = true;
            } else {
                $send['error'] = '密码修改失败';
            }

        } while(false);
        $this->output->send($send);
    }

    public function detail()
    {
        $send['state'] = false;
        do {

            $id = $this->input->get('id');
            if (empty($id)) {
                $send['error'] = '参数错误';
                break;
            }

            $q = $this->db->where('a.id', $id)->join('admin_profile as p', 'p.adminId = a.id')->get('admin as a');
            $item = $q->row_array();
            if (empty($item)) {
                $send['error'] = '管理员不存在';
                break;
            }

            $item['thumbView'] = thumb($item['avatar'], 200, 200);
            $send['state'] = true;
            $send['data'] = $item;
        } while(false);
        $this->output->send($send);
    }

    /**
     * 删除
     */
    public function delete()
    {
        $send['state'] = false;
        do {

            $id = $this->input->get('id');
            if (empty($id)) {
                $send['error'] = '参数错误';
                break;
            }

            $db = clone ($this->db);
            $db->where('id', $id);
            $db->delete('admin');

            $db2 = clone ($this->db);
            $db2->where('adminId', $id);
            $db2->delete('admin_profile');

            if ($db->affected_rows() && $db2->affected_rows()) {
                $send['state'] = true;
            } else {
                $send['error'] = '操作失败';
            }

        } while(false);
        $this->output->send($send);
    }


    /**
     * 主程序
     */
    public function index()
    {
        $page = (int) $this->input->get('page');
        $page = empty($page) ? 1 : $page;

        $admin = $this->input->get('admin', '');
        $offset = ($page - 1) * self::DEFAULT_LIMIT;

        $this->load->model('admin/system/Admin_Model', 'admin');
        $res = $this->admin->getLists(array(
            'limit' => self::DEFAULT_LIMIT,
            'offset' => $offset,
            'admin' => $admin,
            'role' => $this->role,
            'baseId' => $this->baseId
        ));

        if (!empty($res['data'])) foreach ($res['data'] as &$item) {
            if ($item['baseId'] > 0) {
                $item['role'] = $item['roleId'] == 0 ? '基地管理员' : '基地负责人';
            }
        }

        $newRoles = [];
        $roles = $this->admin->getRoles();
        if (!empty($roles)) foreach ($roles as $key => $role) {
            if ($role['id'] == 1) {
                continue;
            }
            $newRoles[] = $role;
        }

        $res = array_merge($res, array('roles' => $newRoles));
        $this->load->view(parent::TMP_DIR . '/admin/user.html', $res);
    }

    public function addAdmin()
    {
        $send['state'] = false;
        do {

            if ($this->input->method(true) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }

            $params = $this->input->post();
            if (empty($params['email'])
                || empty($params['nickname']) || empty($params['phone'])
                || empty($params['password'])) {

                $send['error'] = '参数错误';
                break;
            }

            if (strlen($params['password']) < 6) {
                $send['error'] = '密码长度不够';
                break;
            }

            $pass = encryptPassword($params['password']);
            $db1 = clone($this->db);

            $q = $db1->get_where('admin', ['email' => $params['email']]);
            if ($q->row_array()) {
                $send['error'] = '该邮箱账号已经存在';
                break;
            }

            $db1->insert('admin', [
                'baseId' => intval($this->baseId),
                'nickName' => value($params, 'nickname'),
                'roleId' => value($params, 'roleid'),
                'email' => value($params, 'email'),
                'password' => $pass['password'],
                'salt' => $pass['salt'],
                'created' => date("Y-m-d H:i:s"),
                'lastTime' => date("Y-m-d H:i:s"),
                'lastIp' => remoteAddr(),
                'status' => 1
            ]);

            $id = $db1->insert_id();
            if (empty($id)) {
                $send['error'] = '用户添加失败';
                break;
            }

            $db2 = clone($this->db);
            $db2->insert('admin_profile', [
                'adminId' => $id,
                'avatar' => $params['thumb'],
                'phone' => $params['phone']
            ]);

            if ($id) {
                $send['state'] = true;
            } else {
                $send['error'] = '创建失败';
            }

        } while(false);

        $this->output->send($send);
    }

    public function editAdmin()
    {
        $send['state'] = false;
        do {
            if ($this->input->method(true) !== 'POST') {
                $send['error'] = '非法请求';
                break;
            }

            $params = $this->input->post();
            if (empty($params['id']) || empty($params['email'])
                || empty($params['nickname']) || empty($params['phone'])) {

                $send['error'] = '参数错误';
                break;
            }

            /*
            $this->load->model('admin/system/Admin_Model', 'admin');
            $res = $this->admin->edit($params);
            */
            $data = [
                'roleId' => $params['roleid'],
                'email' => $params['email'],
                'nickName' => $params['nickname']
            ];
            if (!empty($params['password'])) {
                if (strlen($params['password']) < 6) {
                    $send['error'] = '密码长度不符';
                    break;
                }
                $pass = encryptPassword($params['password']);
                $data['password'] = $pass['password'];
                $data['salt'] = $pass['salt'];
            }

            $db1 = clone ($this->db);
            $db1->where('id', $params['id'])->update('admin', $data);

            $db2 = clone($this->db);
            $db2->where('adminId', $params['id'])->update('admin_profile', [
                'avatar' => $params['thumb'],
                'phone' => $params['phone']
            ]);

            if ($db1->affected_rows() || $db2->affected_rows()) {
                $send['state'] = true;
            } else {
                $send['error'] = '修改失败';
            }

        } while(false);

        $this->output->send($send);
    }

    /**
     * 头像上传
     */
    public function upLoad()
    {
        $send['state'] = false;
        do {
            $res = local($_FILES['file']);
            if (!$res) {
                $err = $this->up->error();
                $send['error'] = !empty($err) ? $err : '头像上传失败';
                break;
            }

            $res['fullPath'] = thumb($res['key'], 100, 100);

            $send['state'] = true;
            $send['data'] = $res;
        } while(false);

        $this->output->send($send);
    }

}